<template>
  <div class="trade-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>策略交易</span>
        </div>
      </template>
      <el-form ref="tradeForm" :model="tradeConfig" label-width="120px">
        <el-form-item label="选择策略" prop="strategyId" :rules="[{ required: true, message: '请选择策略', trigger: 'change' }]">
          <el-select v-model="tradeConfig.strategyId" placeholder="请选择策略">
            <el-option v-for="strategy in strategies" :key="strategy.id" :label="strategy.name" :value="strategy.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易对" prop="symbol" :rules="[{ required: true, message: '请选择交易对', trigger: 'change' }]">
          <el-select v-model="tradeConfig.symbol" placeholder="请选择交易对">
            <el-option label="BTCUSDT" value="BTCUSDT" />
            <el-option label="ETHUSDT" value="ETHUSDT" />
            <el-option label="SOLUSDT" value="SOLUSDT" />
          </el-select>
        </el-form-item>
        <el-form-item label="资金比例(%)" prop="capitalRatio" :rules="[{ required: true, message: '请输入资金比例', trigger: 'blur' }, { type: 'number', min: 1, max: 100, message: '资金比例必须在1-100之间', trigger: 'blur' }]">
          <el-input v-model.number="tradeConfig.capitalRatio" placeholder="请输入资金比例" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isTrading" :disabled="isTrading" @click="startTrade">启动策略</el-button>
          <el-button type="danger" :loading="!isTrading" :disabled="!isTrading" @click="stopTrade">停止策略</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="trade-info">
      <el-card class="position-card">
        <template #header>
          <div class="card-header">
            <span>当前持仓</span>
          </div>
        </template>
        <el-table :data="positions" style="width: 100%">
          <el-table-column prop="symbol" label="交易对" width="100" />
          <el-table-column prop="qty" label="数量" width="100" />
          <el-table-column prop="avgPrice" label="平均价格" width="120" />
          <el-table-column prop="currentPrice" label="当前价格" width="120" />
          <el-table-column prop="profit" label="浮动盈亏" width="120">
            <template #default="{ row }">
              <span :class="{ 'profit-positive': row.profitType === 'positive', 'profit-negative': row.profitType === 'negative' }">{{ row.profit }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="trade-log-card">
        <template #header>
          <div class="card-header">
            <span>交易记录</span>
          </div>
        </template>
        <el-table :data="tradeLogs" style="width: 100%">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="symbol" label="交易对" width="100" />
          <el-table-column prop="side" label="方向" width="80">
            <template #default="{ row }">
              <span :class="{ 'buy-tag': row.side === 'BUY', 'sell-tag': row.side === 'SELL' }">{{ row.side }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="120" />
          <el-table-column prop="qty" label="数量" width="100" />
          <el-table-column prop="amount" label="金额" width="120" />
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalLogs"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';

const tradeForm = ref(null);
const strategies = ref([]);
const positions = ref([]);
const tradeLogs = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalLogs = ref(0);
const isTrading = ref(false);
const tradeConfig = reactive({
  strategyId: '',
  symbol: '',
  capitalRatio: 50
});

// 模拟数据
const mockStrategies = [
  { id: 1, name: 'MACD交叉策略' },
  { id: 2, name: 'RSI超买超卖策略' },
  { id: 3, name: '布林带策略' }
];

onMounted(() => {
  fetchStrategies();
  fetchPositions();
  fetchTradeLogs();
});

function fetchStrategies() {
  // 模拟API请求
  setTimeout(() => {
    strategies.value = mockStrategies;
  }, 500);
}

function fetchPositions() {
  // 模拟API请求
  setTimeout(() => {
    positions.value = [
      { symbol: 'BTCUSDT', qty: 0.025, avgPrice: '¥40,000.00', currentPrice: '¥42,356.78', profit: '¥589.19', profitType: 'positive' },
      { symbol: 'ETHUSDT', qty: 0.5, avgPrice: '¥2,000.00', currentPrice: '¥2,156.34', profit: '¥78.17', profitType: 'positive' }
    ];
  }, 500);
}

function fetchTradeLogs() {
  // 模拟API请求
  setTimeout(() => {
    const logs = [];
    for (let i = 0; i < 15; i++) {
      const date = new Date();
      date.setMinutes(date.getMinutes() - i * 30);
      const time = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      const side = i % 2 === 0 ? 'BUY' : 'SELL';
      const price = 40000 + Math.random() * 5000;
      const qty = 0.01 + Math.random() * 0.05;
      const amount = price * qty;

      logs.push({
        time,
        symbol: 'BTCUSDT',
        side,
        price: `¥${price.toFixed(2)}`,
        qty: qty.toFixed(4),
        amount: `¥${amount.toFixed(2)}`
      });
    }
    tradeLogs.value = logs;
    totalLogs.value = logs.length;
  }, 500);
}

function startTrade() {
  tradeForm.value.validate((valid) => {
    if (valid) {
      // 模拟启动策略
      isTrading.value = true;
      ElMessage({
        type: 'success',
        message: '策略启动成功'
      });
      // 模拟策略交易，定期更新交易记录
      simulateTrading();
    } else {
      return false;
    }
  });
}

function stopTrade() {
  // 模拟停止策略
  isTrading.value = false;
  ElMessage({
    type: 'success',
    message: '策略停止成功'
  });
  // 清除定时器
  if (window.tradeTimer) {
    clearInterval(window.tradeTimer);
    window.tradeTimer = null;
  }
}

function simulateTrading() {
  // 清除之前的定时器
  if (window.tradeTimer) {
    clearInterval(window.tradeTimer);
  }
  // 设置新的定时器，模拟交易
  window.tradeTimer = setInterval(() => {
    const date = new Date();
    const time = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    const side = Math.random() > 0.5 ? 'BUY' : 'SELL';
    const price = 40000 + Math.random() * 5000;
    const qty = 0.01 + Math.random() * 0.05;
    const amount = price * qty;

    // 添加新的交易记录
    tradeLogs.value.unshift({
      time,
      symbol: tradeConfig.symbol,
      side,
      price: `¥${price.toFixed(2)}`,
      qty: qty.toFixed(4),
      amount: `¥${amount.toFixed(2)}`
    });
    totalLogs.value++;

    // 更新持仓
    updatePositions(side, price, qty);
  }, 5000); // 每5秒模拟一次交易
}

function updatePositions(side, price, qty) {
  // 查找是否已经有该交易对的持仓
  const positionIndex = positions.value.findIndex(item => item.symbol === tradeConfig.symbol);

  if (side === 'BUY') {
    if (positionIndex > -1) {
      // 已有持仓，更新平均价格
      const position = positions.value[positionIndex];
      const currentQty = parseFloat(position.qty);
      const currentAvgPrice = parseFloat(position.avgPrice.replace(/[^\d.]/g, ''));
      const newQty = currentQty + qty;
      const newAvgPrice = ((currentQty * currentAvgPrice) + (qty * price)) / newQty;
      const currentPrice = parseFloat(price.toFixed(2));
      const profit = ((currentPrice - newAvgPrice) * newQty).toFixed(2);
      const profitType = profit >= 0 ? 'positive' : 'negative';

      positions.value[positionIndex] = {
        ...position,
        qty: newQty.toFixed(4),
        avgPrice: `¥${newAvgPrice.toFixed(2)}`,
        currentPrice: `¥${currentPrice.toFixed(2)}`,
        profit: `¥${Math.abs(profit).toFixed(2)}`,
        profitType
      };
    } else {
      // 新的持仓
      const currentPrice = parseFloat(price.toFixed(2));
      positions.value.push({
        symbol: tradeConfig.symbol,
        qty: qty.toFixed(4),
        avgPrice: `¥${price.toFixed(2)}`,
        currentPrice: `¥${currentPrice.toFixed(2)}`,
        profit: '¥0.00',
        profitType: 'positive'
      });
    }
  } else if (side === 'SELL') {
    if (positionIndex > -1) {
      // 已有持仓，减少数量
      const position = positions.value[positionIndex];
      const currentQty = parseFloat(position.qty);
      const newQty = currentQty - qty;

      if (newQty <= 0) {
        // 清空持仓
        positions.value.splice(positionIndex, 1);
      } else {
        // 更新持仓数量
        const currentPrice = parseFloat(price.toFixed(2));
        const avgPrice = parseFloat(position.avgPrice.replace(/[^\d.]/g, ''));
        const profit = ((currentPrice - avgPrice) * qty).toFixed(2);
        const totalProfit = parseFloat(position.profit.replace(/[^\d.]/g, '')) + parseFloat(profit);
        const profitType = totalProfit >= 0 ? 'positive' : 'negative';

        positions.value[positionIndex] = {
          ...position,
          qty: newQty.toFixed(4),
          currentPrice: `¥${currentPrice.toFixed(2)}`,
          profit: `¥${Math.abs(totalProfit).toFixed(2)}`,
          profitType
        };
      }
    }
  }
}

function handleSizeChange(val) {
  pageSize.value = val;
  fetchTradeLogs();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  fetchTradeLogs();
}
</script>

<style scoped>
.trade-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trade-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.position-card,
.trade-log-card {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.buy-tag {
  color: #27AE60;
  font-weight: bold;
}

.sell-tag {
  color: #E74C3C;
  font-weight: bold;
}

.profit-positive {
  color: #27AE60;
  font-weight: bold;
}

.profit-negative {
  color: #E74C3C;
  font-weight: bold;
}
</style>